<template>
  <div>
    <el-dialog v-model="openFlag" title="派发单" width="70%" append-to-body>
      <el-form :model="formData" :rules="rules" label-width="80">
        <el-form-item label="领用人" prop="targetUserId">
          <user-select v-model="formData.targetUserId"></user-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="formData.remark" placeholder="请输入" />
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              type="primary"
              plain
              icon="Search"
              @click="handleChoose"
          >选择资产</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="tableData.loading" :data="tableData.list">

        <el-table-column width="120" label="图片" align="center" prop="number">
          <template #default="scope">
            <el-tooltip v-if="scope.row.imgUrl"
                        class="box-item"
                        effect="dark"
                        placement="right-start"
            >
              <template #content>
                <img alt="" :src="showImg(scope.row.imgUrl)" width="100" height="100" />
              </template>
              <img alt="" :src="showImg(scope.row.imgUrl)" width="30" height="30" />
            </el-tooltip>
            <span v-else>没有图片</span>
          </template>
        </el-table-column>

        <el-table-column width="120" label="编码" align="center" prop="number"/>
        <el-table-column width="180" label="名称" align="center" prop="name"/>
        <el-table-column width="180" label="数量" align="center" prop="num">
          <template #default="scope">
            <el-input v-model="scope.row.num"></el-input>
          </template>
        </el-table-column>
        <el-table-column width="120" label="分类" align="center" prop="categoryName"/>
        <el-table-column width="120" label="商品条码" align="center" prop="barcode"/>
        <el-table-column width="120" label="品牌" align="center" prop="brand"/>
        <el-table-column width="120" label="规格型号" align="center" prop="model"/>

        <el-table-column label="操作" align="center" fixed="right">
          <template  #default="scope">
            <el-button
                link
                type="primary"
                @click="handleDelete(scope)"
            >删除</el-button>

          </template>
        </el-table-column>

      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-row type="flex" justify="end">
          <el-button type="primary" @click="save">保存</el-button>
          <el-button type="primary" @click="sub">提交</el-button>
          <el-button @click="close">取 消</el-button>
        </el-row>

      </div>
    </el-dialog>

    <choose-file-dialog v-if="openFlag" ref="chooseDialog" @sub="onChooseSub"></choose-file-dialog>

  </div>
</template>

<script setup>

import api from "@/api/consume/inApply.js";
import ChooseFileDialog from "./ChooseFileDialog.vue";
import UserSelect from "@/components/User/UserSelect.vue";

const { proxy } = getCurrentInstance();
const emit = defineEmits(['sub']);

const chooseDialog = ref();

const openFlag = ref(false);
const tableData = reactive({
  loading: false,
  list: []
});

const rules = reactive({
  targetUserId: [{ required: true, message: "不能为空", trigger: "blur" }]
});

const formDataInit = {
  applyType: 'HCPF',
  targetUserId: null,
}

let actionType = '';
let deletedItem = [];

const isEdit = ref(false);
const formData = reactive({...formDataInit});

function getTotalPrice(row) {
  if (!row.price || !row.num) {
    return 0;
  }
  return row.price * row.num;
}

function reset() {
  Object.assign(formData, formDataInit);
  tableData.list = [];
  deletedItem = [];
}

function open(row) {

  openFlag.value = true;
  reset();

  if (row) {
    isEdit.value = true;
    const id = row.id;
    api.detail(id).then(response=> {
      Object.assign(formData, response);
    });

    api.detailRelItems(id).then(response=> {
      tableData.list = response;
    })
    actionType = 'edit';

  } else {
    isEdit.value = false;
    actionType = 'add';
  }
}

function close() {
  openFlag.value = false;
}

function showImg(img) {
  return import.meta.env.VITE_APP_BASE_API + img;
}

function handleChoose() {
  chooseDialog.value.open();
}
function handleDelete({ row, $index }) {
  // 如果是编辑状态需要把删除的行存起来
  if (actionType === 'edit') {
    deletedItem.push(row);
  }
  tableData.list.splice($index, 1);
}
/** 提交按钮 */
function save() {
  const apply = {
    apply: { ...formData },
    items: tableData.list,
    itemsDel: deletedItem
  }
  api.save(actionType, apply).then(() => {
    emit("sub");
    close();
  });
}
function sub() {
  const items = tableData.list;
  if (!items || items.length === 0) {
    return proxy.$modal.alert('还没有填写你申请的清单');
  }
  items.forEach(item=> {
    item.totalPrice = getTotalPrice(item);
  })
  debugger
  const apply = {
    apply: { ...formData },
    items: tableData.list,
    itemsDel: deletedItem
  }
  api.saveAndSub(actionType, apply).then(() => {
    emit("sub");
    close();
  });
}

function onChooseSub(selected) {
  if (selected) {
    selected.forEach((item)=> {
      let row = {...item};
      row.fileId = row.id;
      delete row.id;
      row.num = 1;
      tableData.list.push(row);
    })
  }
}

defineExpose({
  open
})


</script>

